package com.suneast.suneaststore.modules.shopcart;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.suneast.suneaststore.MainActivity;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.bean.personal.wallet.WeChatPayBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.GotUserInfo;
import com.suneast.suneaststore.modules.personal.PersonHandler;
import com.suneast.suneaststore.modules.personal.PersonalFragment;
import com.suneast.suneaststore.modules.personal.order.fragment.PurchaseManage;
import com.suneast.suneaststore.modules.personal.wallet.WalletHandler;
import com.suneast.suneaststore.modules.personal.wallet.event.BalanceValueChange;
import com.suneast.suneaststore.modules.shopcart.event.BalancePayResult;
import com.suneast.suneaststore.modules.shopcart.event.GotPayInfo;
import com.suneast.suneaststore.modules.shopcart.event.GotWeChatPayData;
import com.suneast.suneaststore.modules.wechat.LatteWeChat;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

import static com.suneast.suneaststore.app.Latte.getApplicationContext;

public class HandlePayFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener {
    @Override
    public int setLayout() {
        return R.layout.fragment_handle_pay;
    }

    private int orderId = 0;

    public HandlePayFragment withId(int orderId) {
        this.orderId = orderId;
        return this;
    }

    @BindView(R.id.toolbar_pay_order)
    public Toolbar payOrderToolbar;

    @BindView(R.id.tv_order_sn)
    public TextView orderSNTv;

    @BindView(R.id.tv_old_pay)
    public TextView oldPayTv;

    @BindView(R.id.tv_deduction_pay)
    public TextView deductionPayTv;

    @BindView(R.id.tv_actually_pay)
    public TextView actuallyPayTv;

    @BindViews({R.id.cb_wechat_pay, R.id.cb_ali_pay, R.id.cb_balance_pay})
    public CheckBox[] payTypeXCbs;

    @BindView(R.id.tv_balance_value)
    public TextView balanceValueTv;

    @BindView(R.id.btn_go_to_pay)
    public Button gotoPayBtn;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
        Log.e(TAG, "onBindView: orderId = " + orderId);
        if (orderId != 0) {
            //请求订单支付信息
            ShopCartHandler.requestPayInfo(orderId);
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private DecimalFormat mDecimalFormat;

    private void initView() {
        mDecimalFormat = new DecimalFormat("0.00");
        payOrderToolbar.setNavigationOnClickListener((View v) -> {
            pop();
        });
        for (CheckBox cb : payTypeXCbs) {
            cb.setOnCheckedChangeListener(this);
        }
    }

    @OnClick({R.id.btn_go_to_pay})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_go_to_pay: {
                switch (payType) {
                    case Flag.PayType.WECHAT_PAY: {
                        Log.e(TAG, "onViewClick: WECHAT_PAY");
                        if (payInfo != null) {
                            gotoPayBtn.setEnabled(false);
                            WalletHandler.requestWeChatPay(payInfo.getOrderId());
                        }
                    }
                    break;
                    case Flag.PayType.BALANCE_PAY: {
                        Log.e(TAG, "onViewClick: BALANCE_PAY");
                        if (payInfo != null) {
                            if (payInfo.getActuallyPay() <= PersonalFragment.balanceValue) {
                                showPassInputDialog();
                            } else {
                                Toast.makeText(_mActivity, "余额额度不足以支付该订单", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;
                    case Flag.PayType.ALI_PAY: {

                    }
                    break;
                }
            }
            break;
        }
    }

    private @Flag.PayType
    int payType;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.cb_wechat_pay:
                    payType = Flag.PayType.WECHAT_PAY;
                    break;
                case R.id.cb_ali_pay:
                    payType = Flag.PayType.ALI_PAY;
                    break;
                case R.id.cb_balance_pay:
                    payType = Flag.PayType.BALANCE_PAY;
                    break;
            }
            setCb(payType);
        }
    }

    private void setCb(@Flag.PayType int payType) {
        for (int i = 0; i < payTypeXCbs.length; i++) {
            if (i != payType) {
                payTypeXCbs[i].setChecked(false);
            }
        }
    }

    GotPayInfo payInfo;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotPayInfo(GotPayInfo payInfo) {
        Log.e(TAG, "onGotPayInfo: orderSN = " + payInfo.getOrderSN());
        this.payInfo = payInfo;
        orderSNTv.setText(payInfo.getOrderSN());
        oldPayTv.setText(String.format(getString(R.string.rmb),
                String.valueOf(payInfo.getTotalPay())));
        deductionPayTv.setText(String.format(getString(R.string.coin_deduction),
                mDecimalFormat.format(payInfo.getDeductionPay())));
        actuallyPayTv.setText(String.format(getString(R.string.rmb),
                mDecimalFormat.format(payInfo.getActuallyPay())));
        PersonHandler.requestPersonInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotUserInfo(GotUserInfo event) {
        PersonalFragment.balanceValue = event.getBalance();
        balanceValueTv.setText(String.format(getString(R.string.rmb),
                mDecimalFormat.format(PersonalFragment.balanceValue)));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotWeChatPayData(GotWeChatPayData weChatPayData) {
        if (weChatPayData.getResult() == Flag.Result.SUCCEED) {
            LatteLogger.e(TAG, "GotWeChatPayData SUCCEED");
            WeChatPayBean payInfoBean = weChatPayData.getDataBean();
            PayReq request = new PayReq();
            request.appId = payInfoBean.getAppid();
            request.partnerId = payInfoBean.getPartnerid();
            request.prepayId = payInfoBean.getPrepayid();
            request.packageValue = payInfoBean.getPackageX();
            request.nonceStr = payInfoBean.getNoncestr();
            request.timeStamp = String.valueOf(payInfoBean.getTimestamp());
            request.sign = payInfoBean.getSign();
            IWXAPI api = LatteWeChat.getInstance().getWXAPI();
            api.sendReq(request);
            pop();
        } else {
            gotoPayBtn.setEnabled(true);
            Toast.makeText(_mActivity, "请求微信支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private EditText inputPassEt;
    private AlertDialog dialog;

    private void showPassInputDialog() {
        if (inputPassEt == null) {
            inputPassEt = new EditText(getContext());
            inputPassEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            dialog = new AlertDialog.Builder(_mActivity)
                    .setTitle("输入密码")
                    .setIcon(R.mipmap.ic_launcher)
                    .setView(inputPassEt)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String input = inputPassEt.getText().toString();
                            if (input.length() < 6) {
                                Toast.makeText(_mActivity, "密码需长度大于6", Toast.LENGTH_SHORT).show();
                            } else {
                                WalletHandler.requestBalancePay(payInfo.getOrderId(), input);
                            }
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create();
        }
        dialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBalancePayResult(BalancePayResult result) {
        if (result.getValue() == Flag.Result.SUCCEED) {
            Toast.makeText(_mActivity, "余额支付成功", Toast.LENGTH_LONG).show();
            PersonalFragment.balanceValue = result.getBalanceValue();
            EventBus.getDefault().post(new BalanceValueChange());
            startWithPop(new PurchaseManage().withId(R.id.tiv_goods_wait_send));
        } else {
            Toast.makeText(_mActivity, "余额支付失败:" + result.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }
}
